package com.market.cash.ui.fragment

import android.view.LayoutInflater
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.market.cash.R
import com.market.cash.databinding.CashHomeBinding
import com.market.cash.pro.ProFragment
import com.market.cash.ui.activity.ApplyActivity
import com.market.cash.ui.activity.KefuActivity
import com.market.cash.ui.activity.OrderDetailsActivity
import com.market.cash.ui.activity.StepsActivity
import com.market.cash.ui.adapter.CashRootHomeAdapter
import com.market.cash.ui.presenter.CashRootHomePresenter
import com.market.cash.ui.view.ICashRootHomeView
import com.market.cash.utils.CashRootBarUtil
import com.market.cash.utils.event.CashRootEventData
import com.market.cash.utils.event.CashRootEventType
import com.market.cash.utils.helper.CashRootCustomConfigsHelper
import com.market.cash.utils.helper.TestDataLibInvoke
import org.json.JSONObject

/**
 * CashRoot
 * @Author wwdeng
 * @CreateTime: 2024/10/18 16:52
 * @Annotation：首页
 */
class HomeFragment: ProFragment(), ICashRootHomeView {
    lateinit var binding: CashHomeBinding
    private var presenter: CashRootHomePresenter? = null
    //产品列表
    private var pAdapter: CashRootHomeAdapter? = null

    override fun getCashRootRootView(inflater: LayoutInflater): View {
        binding = CashHomeBinding.inflate(inflater)
        return binding.root
    }

    override fun initCashRootView() {
        binding.parentLayout.setPadding(0,CashRootBarUtil.getStatusBarHeight(),0,0)
        initCashRootRefreshLayout()
        initCashRootRecyclerView()
    }

    override fun initCashRootListener() {
        //客服
        binding.imgKefu.setOnClickListener {
            KefuActivity.start(requireContext(),"Home Page")
            addCashRootEventPoint(CashRootEventType.CLICK.CASHROOT_CLICK_CUSTOMER,"Home Page")
        }
    }

    override fun initCashRootData() {
        presenter = CashRootHomePresenter(this)
        presenter!!.loadCashRootAllPermissionsAction()
        presenter!!.loadCashRootProductListAction()

        //牌照信息
        if (!CashRootCustomConfigsHelper.isCashRootShowLicense()){
            binding.licenseLayout.removeAllViews()
            binding.licenseLayout.visibility = View.GONE
        } else {
            binding.licenseLayout.removeAllViews()
            binding.licenseLayout.addView(initCashRootLicenseView())
            binding.licenseLayout.visibility = View.VISIBLE
        }
    }

    /* 初始化刷新 */
    private fun initCashRootRefreshLayout() {
        //禁止加载
        binding.refreshLayout.setEnableLoadMore(false)
        binding.refreshLayout.setEnableAutoLoadMore(false)
        binding.refreshLayout.setOnRefreshListener {
            //刷新产品列表
            getAct().publishEventData(CashRootEventData(CashRootEventData.TYPE.CASHROOT_PRODUCT_REFRESH))
        }
        binding.refreshLayout.setOnLoadMoreListener {
            binding.refreshLayout.finishLoadMore()
        }
    }

    /**
     * 产品列表
     */
    private fun initCashRootRecyclerView(){
//        binding.recyclerView.setHasFixedSize(true)
//        binding.recyclerView.isNestedScrollingEnabled = false
//        binding.recyclerView.isFocusableInTouchMode = false //不需要焦点
        val layoutManager = LinearLayoutManager(context)
        binding.recyclerView.layoutManager = layoutManager
        pAdapter = CashRootHomeAdapter(binding.recyclerView)
        pAdapter!!.setOnItemChildClickListener { _, childView, position ->
            val item = this.pAdapter!!.getItem(position)
            presenter!!.setCashRootSelectProduct(item)
            when(childView.id){
                R.id.repayLayout -> {//待还款
                    getAct().publishEventData(CashRootEventData(CashRootEventData.TYPE.CASHROOT_SHOW_REPAY))
                }
                R.id.btnApply -> {//申贷
                    showCashRootLoading()
                    presenter!!.checkCashRootAllPermissionsAgree()
                }
                R.id.inReviewLayout,
                R.id.rejectedLayout -> {//审核中、放款中、已拒绝
                    val pLogo = item.optString("logo")
                    val pName = item.optString("product")
                    val pToken = item.optString("token")
                    val pTitle = item.optString("name")
                    OrderDetailsActivity.start(requireContext(), pLogo, pName, pToken,pTitle)
                }
            }
        }
        binding.recyclerView.adapter = pAdapter
    }

    /**
     * 设置产品列表
     */
    override fun showCashRootProductList(pList: ArrayList<JSONObject>) {
        pAdapter!!.data = pList
    }

    /**
     * 所有权限校验成功
     */
    override fun showCashRootCheckPermissionSuccess() {
        //上报
        TestDataLibInvoke.sycData()
        presenter!!.checkCashRootAllStepsAction()
    }

    /**
     * 认证已完成 - 进入申贷页面
     */
    override fun showCashRootLoanApplyPage(pName: String, pToken: String) {
        //刷新主流程，防止SMS校验不正确
        publishEventData(CashRootEventData(CashRootEventData.TYPE.CASHROOT_PROCESS_REFRESH))
        hideCashRootLoading()
        ApplyActivity.start(requireContext(),pName,pToken)
    }

    /**
     * 认证未完成 - 进入认证页面
     */
    override fun showCashRootProcessStepsPage() {
        hideCashRootLoading()
        onIntent(StepsActivity::class.java)
    }

    override fun onCashRootEvent(event: CashRootEventData) {
        super.onCashRootEvent(event)
        when(event.eventType){
            CashRootEventData.TYPE.CASHROOT_PRODUCT_REFRESHED -> {//刷新产品列表完成
                presenter!!.loadCashRootProductListAction()


            }
            CashRootEventData.TYPE.CASHROOT_PRODUCT_FINISHED -> {
                hideCashRootLoading()
                presenter!!.loadCashRootProductListAction()

            }
            else -> {

            }
        }
    }

    override fun hideCashRootLoading() {
        super.hideCashRootLoading()
        binding.refreshLayout.finishRefresh()
    }

    override fun onStart() {
        super.onStart()
        addCashRootEventPoint(CashRootEventType.PAGE.CASHROOT_PAGE_PRODUCT_LIST_START)
    }

    override fun onDestroy() {
        super.onDestroy()
        addCashRootEventPoint(CashRootEventType.PAGE.CASHROOT_PAGE_PRODUCT_LIST_END)
    }
}